// utils/timerManager.js
// 定时器管理工具类

class TimerManager {
  constructor() {
    this.timers = new Map(); // 存储所有定时器
  }

  // 设置提醒定时器
  scheduleReminder(reminder, playCallback) {
    if (!reminder.isActive) return;

    // 清除已存在的定时器
    this.clearReminder(reminder.id);

    let interval;
    switch (reminder.frequency) {
      case 'hourly':
        interval = 60 * 60 * 1000; // 1小时
        this.setRepeatingTimer(reminder.id, interval, playCallback);
        break;
      case 'custom':
        interval = reminder.interval * 60 * 1000; // 自定义分钟数
        this.setRepeatingTimer(reminder.id, interval, playCallback);
        break;
      case 'daily':
        this.setDailyTimers(reminder.id, reminder.times, playCallback);
        break;
    }
  }

  // 设置重复定时器
  setRepeatingTimer(id, interval, callback) {
    const timer = setInterval(() => {
      callback();
    }, interval);
    
    this.timers.set(id, {
      timer,
      type: 'repeating',
      interval
    });
  }

  // 设置每日多个时间点定时器
  setDailyTimers(id, timeStrs, callback) {
    const timerIds = [];
    timeStrs.forEach((timeStr, index) => {
      const scheduleNext = () => {
        const nextInterval = this.calculateDailyInterval(timeStr);
        const timer = setTimeout(() => {
          callback();
          scheduleNext(); // 递归设置下次提醒
        }, nextInterval);

        const timerId = `${id}-${index}`;
        timerIds.push(timerId);
        this.timers.set(timerId, {
          timer,
          type: 'daily',
          timeStr
        });
      };
      scheduleNext();
    });

    // 为了能够统一清除，我们将这一组timerId关联到主id
    this.timers.set(id, { type: 'daily-group', timerIds });
  }

  // 计算每日间隔时间
  calculateDailyInterval(timeStr) {
    const [hours, minutes] = timeStr.split(':').map(Number);
    const now = new Date();
    const target = new Date();
    target.setHours(hours, minutes, 0, 0);

    // 如果目标时间已过，设置为明天
    if (target <= now) {
      target.setDate(target.getDate() + 1);
    }

    return target.getTime() - now.getTime();
  }

  // 清除指定提醒的定时器
  clearReminder(id) {
    const timerInfo = this.timers.get(id);
    if (timerInfo) {
      if (timerInfo.type === 'repeating') {
        clearInterval(timerInfo.timer);
        this.timers.delete(id);
      } else if (timerInfo.type === 'daily') {
        clearTimeout(timerInfo.timer);
        this.timers.delete(id);
      } else if (timerInfo.type === 'daily-group') {
        // 如果是每日提醒组，清除所有关联的定时器
        timerInfo.timerIds.forEach(timerId => {
          const singleTimerInfo = this.timers.get(timerId);
          if (singleTimerInfo) {
            clearTimeout(singleTimerInfo.timer);
            this.timers.delete(timerId);
          }
        });
        this.timers.delete(id);
      }
    }
  }

  // 暂停提醒
  pauseReminder(id) {
    this.clearReminder(id);
  }

  // 恢复提醒
  resumeReminder(reminder, playCallback) {
    this.scheduleReminder(reminder, playCallback);
  }

  // 清除所有定时器
  clearAll() {
    this.timers.forEach((timerInfo, id) => {
      this.clearReminder(id);
    });
  }

  // 获取定时器状态
  getTimerStatus(id) {
    return this.timers.has(id);
  }

  // 获取所有活跃的定时器ID
  getActiveTimers() {
    return Array.from(this.timers.keys());
  }

  // 格式化频率文本
  static getFrequencyText(frequency, times, interval) {
    switch (frequency) {
      case 'daily':
        return `每日 ${times.join(', ')}`;
      case 'hourly':
        return '每小时';
      case 'custom':
        return `每${interval}分钟`;
      default:
        return '未知频率';
    }
  }

  // 验证时间格式
  static validateTime(timeStr) {
    const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
    return timeRegex.test(timeStr);
  }

  // 验证间隔时间
  static validateInterval(interval) {
    return Number.isInteger(interval) && interval > 0 && interval <= 1440; // 最大24小时
  }
}

module.exports = TimerManager;